package com.wencst.generateJPA.builder.java;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

import com.wencst.generateJPA.bean.TableBean;
import com.wencst.generateJPA.bean.TransferBean;
import com.wencst.generateJPA.builder.IBuilder;
import com.wencst.generateJPA.builder.web.AbstractHtmlBuilder;
import com.wencst.generateJPA.config.CoreContext;

import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public abstract class AbstractJavaBuilder implements IBuilder {
	protected CoreContext coreContext;
	private TransferBean tb;
	
	public AbstractJavaBuilder(CoreContext coreContext) {
		this.coreContext = coreContext;
		tb = new TransferBean();
		TableBean table = coreContext.getTb();
		tb.setColumns(table.getColumns());
		tb.setComment(table.getComment());
		tb.setJavaBeanName(table.getJavaBeanName());
		tb.setTableName(table.getTableName());
		tb.setAuthor(coreContext.getAuthorName());
		tb.setThisPackage(this.getPackage());
	}
	/**
	 * 模板文件存放位置：/templates/freemaker/java
	 * 
	 */
	@SuppressWarnings("deprecation")
	@Override
	public void build() {
        Configuration configuration = new Configuration();
        Writer out = null;
        try {
            configuration.setClassForTemplateLoading(AbstractHtmlBuilder.class, "/templates/freemaker/java");
            Template template = configuration.getTemplate(getTempleName()+".ftl");
            String folder = getDirName();
            File folderFile = new File(folder);
            if (!folderFile.exists()) {
            	folderFile.mkdirs();
            }
            File docFile = new File(folder, getJavaName()+".java");
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
            template.process(tb, out);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        } finally {
            try {
                if (null != out) {
                    out.flush();
                }
            } catch (Exception e2) {
                log.error(e2.getMessage(),e2);
            }
            try {
                if (null != out) {
                    out.close();
                }
            } catch (Exception e2) {
                log.error(e2.getMessage(),e2);
            }
            log.info("complete building java file —— {}",getJavaName());;
        }
	}
	
    /**
     * 获取当前java package
     * @auth wencst
     * @date 2018年9月25日
     * @return
     */
    public abstract String getPackage() ;
	
	/**
	 * 获取java类名（文件名）
	 * @auth wencst
	 * @date 2018年9月25日
	 * @return
	 */
	
	protected abstract String getJavaName();
	
	/**
	 * 获取java文件模板名称
	 * @auth wencst
	 * @date 2018年9月25日
	 * @return
	 */
	
	protected abstract String getTempleName();
}
